from typing import Optional
from fastapi import APIRouter
from fastapi import Depends
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from core.database import get_db
from core.security import get_current_active_user
from db.models.users import UserCreate
from db.mysql.users import Users
from services.user_service import UserService
from services.wx_friends_service import delete_wx_friends
from services.wx_user_service import delete_wx_user
from utils.result import Result

router = APIRouter()

@router.post("/register")
async def register(user_data: UserCreate, db: Session = Depends(get_db)):
    """用户注册"""
    result = await UserService.create_user(user_data, db=db)
    return result

@router.post("/auth/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends(),db: Session = Depends(get_db)):
    """用户登录"""
    result = await UserService.login_user(form_data.username, form_data.password, db)
    return result

@router.get("/me")
async def read_users_me(current_user: Users = Depends(get_current_active_user)):
    """获取当前用户信息"""
    result = await UserService.get_current_user_info(current_user)
    return result

@router.get("/users/{user_id}")
async def get_user(user_id: str, db: Session = Depends(get_db)):
    """获取指定用户信息"""
    # 可以添加权限检查，例如只有管理员或用户自己可以查看
    result = await UserService.get_user_by_id(user_id, db)
    return result

@router.get("/users/{user_id}/wx_users")
async def get_user_wx_list(user_id: str):
    """获取指定用户微信列表"""
    # 可以添加权限检查，例如只有管理员或用户自己可以查看
    result = await UserService.get_wx_list_by_user_id(user_id)
    return result

@router.get("/users")
async def get_users(skip: int = 0, limit: int = 100, username: Optional[str] = None,
                    db: Session = Depends(get_db)):
    """用户列表"""
    result = await UserService.get_users_list(skip=skip, limit=limit, username=username, db=db)
    return result

@router.delete("/users/{user_id}")
async def delete_user(user_id: str,current_user: Users = Depends(get_current_active_user),
                      db: Session = Depends(get_db)):
    """删除用户"""
    # 可以添加权限检查，例如只有管理员可以删除
    if current_user.username != "admin" and str(current_user.user_id) != user_id:
        return Result.fail(code=403,msg="无权限")
    #将rag的微信用户和微信朋友清空
    user_result: Result = await UserService.get_user_by_id(user_id,db)
    device_id = f"rag_{user_result.data.username}"
    await delete_wx_user(device_id)
    await delete_wx_friends(device_id)
    result = await UserService.delete_user(user_id)
    return result



@router.post("/qw/auth/app/login")
async def logout(data:dict):
    """安卓应用软件登录接口"""

    return Result.success(msg="ok")
